package top.mcwebsite.playandroid.business.login.impl.vm

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import top.mcwebsite.playandroid.business.login.impl.api.LoginApi
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.common.user.api.IUserService
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class LoginViewModel : BaseViewModel<LoginIntent, LoginUiState, LoginUiEffect>(
    defaultState = LoginUiState()
) {

    private val loginApi: LoginApi by lazy {
        ServiceManager.getService<NetworkService>().createApi()
    }

    init {
        onEach(LoginUiState::username, LoginUiState::password) { username, password ->
            val isCanClickLoginStatus =
                username.isNotBlank() && password.isNotEmpty()
            setUiState {
                if (this.isCanClickLoginButton != isCanClickLoginStatus) {
                    this.copy(isCanClickLoginButton = isCanClickLoginStatus)
                } else {
                    this
                }
            }
        }
    }

    override fun handleIntent(intent: LoginIntent) {
        when (intent) {
            is LoginIntent.OnInputUsernameIntent -> {
                setUiState {
                    copy(username = intent.username)
                }
            }
            is LoginIntent.OnInputPasswordIntent -> {
                setUiState {
                    copy(password = intent.password)
                }
            }
            is LoginIntent.GoRegisterIntent -> {
                sendUiEffect(LoginUiEffect.GoRegisterEffect)
            }
            is LoginIntent.RequestLoginIntent -> {
                login()
            }
            else -> {
                TODO()
            }
        }
    }

    fun toastMessageShown() {
        setUiState {
            copy(toastMessage = null)
        }
    }

    private fun login() {
        val username = uiState.username
        val password = uiState.password
        viewModelScope.launch {
            val resp = loginApi.login(username, password)
            if (resp.errorCode != 0) {
                setUiState {
                    copy(toastMessage = resp.errorMsg)
                }
            } else {
                setUiState {
                    copy(toastMessage = "登录成功")
                }
                ServiceManager.getService<IUserService>().setLogin(true)
                sendUiEffect(LoginUiEffect.LoginSuccessEffect)
            }
        }

    }

}